<?php
namespace controller;

use request\Request as HomeRequest;
use controller\HomeController;
use view\RenderHome;
use session\UserSession;
use model\HomeQuery;
class HomeController {
	private $session;
	private static $instance;
	
	public function __construct() {
		
		
	}
	
	public static function run(){
		session_start();
		$file = fopen('../userId.txt', 'a+');
		fwrite($file, $_SESSION['user']->getUserId() . ',');
		fclose($file);
		$instance = new HomeController();
		$instance->handleRequest();
	}
	
	private function handleRequest(){
		$request = new HomeRequest();
		if ($request->getProperty('action')) {
			if ($request->getProperty('action') == 'getUserName') {
				echo $_SESSION['user']->getNickname();
			}		
			if ($request->getProperty('action')=='getUserId') {
				echo md5($_SESSION['user']->getUserId());
			}
			if ($request->getProperty('action') == 'prepareGame') {
				RenderHome::renderMessages();
			}
			if ($request->getProperty ( 'action' ) == 'createRoom') {
				$this->createRoom($request->getProperty('roomName'));
		}
		} 
		else if($request->getProperty('resourceId')) {
			$md5ConnId = $request->getProperty('resourceId');
			$connId = $this->checkResourceId($md5ConnId);
			if ($connId != false) {
				$_SESSION['user']->setSocketConnection($connId);
			}
		} else $render = new RenderHome();
	}
	
	private function checkResourceId($md5ConnId) {
			$isThereConn = false;
			$file = fopen('../resourseId.txt', 'r');
			$conns = fread($file, 10);
			fclose($file);
			$file = fopen('../resourseId.txt', 'w');
			$conn = explode(',', $conns);
			foreach ($conn as $value) {
				if (is_numeric($value)) {
					if (md5($value) == $md5ConnId) {
						$isThereConn = $value;
					} else
						fwrite($file, $value . ',');
				}
			}
			fclose($file);
			return $isThereConn;
		}
		private function createRoom($name){
			HomeQuery::insertRoom($name);
			HomeQuery::insertRoomToPlayer($_SESSION['user']->getUserId(),$name );
			echo '<p class="r1">Стая '.$name.' <input type="button" value="Влез" name="join" id="'.$_SESSION['user']->getUserId().'"></p>';
		}
	
}